#!/usr/bin/env perl

# Get stats from partitions
# Basile Clout, December 2007

use Getopt::Long;

use strict;
use warnings;

sub usage(){
  print <<EOF;

Usage: ./statPart.pl [-f list of partitions] [--eet only print max
eet] [--ce only print ce] [-s take G and Rref parameters from the
file] [-g pagrid G parameter] <.graph file> <.vmap file> [<list of
.part file>]

EOF
  exit;
}

#my $partInfo=" /Users/basileclout/Desktop/repo/cutedges/partInfo";
#my $setRef_bin="/Users/basileclout/Desktop/repo/setRef.sh";
my $partInfo="./partInfo";
my $setRef_bin="./setRef.sh";

my $help;
my ($eet, $ce);
my $fparts="";
my ($fgraph, $fvmap);
my @fparts_l;
my $g=10;
my $s;
my $stats;

# Get options
GetOptions("h"=>\$help, "eet"=>\$eet, "ce"=>\$ce, "stats"=>\$stats, "f=s"=>\$fparts, "g=i"=>\$g, "s"=>\$s);

if(($#ARGV < 2 && $fparts eq "") || $help){
  usage;
}

$fgraph=$ARGV[0];
$fvmap=$ARGV[1];
die("Node file \"$fgraph\" is not readable") if (! -r $fgraph);
die("Element file \"$fvmap\" is not readable") if (! -r $fvmap); 

if ($#ARGV > 1){
  @fparts_l=@ARGV[2..$#ARGV];
}elsif ($fparts ne ""){
  open(FPARTS, $fparts) or die("Impossible to open partitions file $fparts: $!");
  @fparts_l=<FPARTS>;
  close(FPARTS);
}

my $order;
my @content;
my @field;
my $vmap_tmp="${fvmap}_tmp";

print "#\tG\tRref\t" if (($eet or $ce) and $s);
print "#\tG\tVmap\t" if (($eet or $ce) and !$s);
print "MaxEET\t" if ($eet);
print "CPU\tBandwidth\tLatency\t" if ($stats);
print "#CE\t" if ($ce);
print "Partition\n" if ($eet or $ce);
my $i=1;

foreach my $part (@fparts_l){
  chomp $part;
  @field = split /\s+/, $part if ($s);
  die("Partition file \"$part\" impossible to read!") if (! -r $part and !$s);
  die("Partition file \"$field[0]\" impossible to read!") if ($s and (! -r $field[0]));
  
  if ($s){
    system("$setRef_bin $field[2] < $fvmap > $vmap_tmp");
    $g = $field[1];
    $order="$partInfo -p -g $g $fgraph $field[0] $vmap_tmp";
  }else{
    $order="$partInfo -p -g $g $fgraph $part $fvmap";
  }
  open(FPART, "$order |") or die "Impossible to successfully execute order $order: $!";
  @content=<FPART>;
  
  if ($eet or $ce){
    if($s){
      print "$i\t$field[1]\t$field[2]\t";
    }else{
      print "$i\t$g\t$fvmap\t";
    }
    foreach my $line (@content){
      chomp $line;
      print "$1\t" if ($line =~ /Max EET:\s+(\d+.\d+)/ and $eet);
      print "$1\t$2\t$3\t" if ($line =~ /Max EET:\s+\d+.\d+\s+\(CPU: (\d+.\d+), Bandwidth: (\d+.\d+), Latency: (\d+.\d+)\)/ and $stats);
      print "$1\t" if ($line =~ /# CE:\s+(\d+)/ and $ce);
    }
    print "$field[0]\n" if ($s);
    print "$part\n" if (!$s);

  }else{
    print @content;
  }

  unlink $vmap_tmp;
  $i++;
}

